import axios from 'axios';
import type { AxiosResponse } from 'axios';
import type { IObject } from './types';

let baseUrl = '';
export function initBaseUrl(url: string) {
  baseUrl = url || '';
}

export function getBaseUrl() {
  return baseUrl;
}

const service = axios.create({
  baseURL: '',
  timeout: 30000
});
service.interceptors.request.use((config) => {
  // 登录接口不需要添加 token
  if (
    !config.url?.startsWith('/oauth/token') &&
    localStorage.getItem('uni_chat_access_token')
  ) {
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('uni_chat_access_token');
  }
  config.headers['Accept-Language'] = 'zh-CN';
  if (baseUrl) {
    config.url = baseUrl + config.url;
  }
  return config;
});

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse<any>) => {
    return res.data;
  },
  (error) => {
    const status = (error.response && error.response.status) || '500';
    const httpCodeLabel: IObject<string> = {
      400: '请求参数错误',
      401: '未授权，请登录',
      403: '拒绝访问',
      404: '请求地址出错',
      408: '请求超时',
      500: 'API接口报500错误',
      501: '服务未实现',
      502: '网关错误',
      503: '服务不可用',
      504: '网关超时',
      505: 'HTTP版本不受支持'
    };
    const errorMsg = httpCodeLabel[status] || '接口错误';
    if (error && error.response) {
      console.log('请求错误', error.response.data);
      return Promise.reject({ code: 9001, msg: error.response.data.msg || errorMsg });
    }
    return Promise.reject({ code: 9001, msg: error.message || '未知错误' });
  }
);

export default service;
